package com.znufe.exam.controller.admin;

import java.util.Date;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.configuration.config.annotation.Log;
import com.znufe.exam.configuration.config.enums.BusinessType;
import com.znufe.exam.service.CourseService;
import com.znufe.exam.utility.PageInfoHelper;
import com.znufe.exam.viewmodel.admin.category.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.znufe.exam.domain.Category;
import com.znufe.exam.service.CategoryService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import com.znufe.exam.base.RestResponse;
import com.znufe.exam.base.SystemCode;

import javax.validation.Valid;

/**   
 * 
 * @Description:  类别信息表接口层
 * @Author:       lin keqing   
 * @CreateDate:   Category
 * @Version:      V1.0
 *    
 */
@Api(description = "类别信息表",value="类别信息表" )
@RestController("AdminCategoryController")
@RequestMapping(value="api/admin/category")
public class CategoryController extends BaseApiController {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private final CategoryService categoryService;

    @Autowired
    private final CourseService courseService;

	public CategoryController(CategoryService categoryService,CourseService courseService) {
		this.categoryService = categoryService;
		this.courseService = courseService;
	}

    @PreAuthorize("@ss.hasAnyPermi('category:course:add,category:course:update,category:project:add,category:project:update')")
    @Log(title = "类别管理", businessType = BusinessType.EDIT)
	@RequestMapping(value="/edit", method = RequestMethod.POST)
	@ApiOperation(value = "类别信息的编辑接口（新增/更新）",
			      notes = "新增/更新类别信息表[category](更新请传入类别id)，作者：lin keqing")
	public RestResponse<Category> edit(@RequestBody @Valid CategoryCreateVM model) {
	    if (model.getId() == null) {
	        Category existCategory = categoryService
                    .selectByConcreteName(model.getConcreteName());
	        if (null != existCategory) {
	            return new RestResponse<>(2, "名称已存在，请更改");
            }
            if (StringUtils.isBlank(model.getConcreteName())) {
                return new RestResponse<>(3, "名称不能为空");
            }
        }

        Category category = modelMapper.map(model, Category.class);
	    if (model.getId() == null) {
	        category.setIsEnabled(1);
	        category.setIsDeleted(0);
	        category.setCreateTime(new Date());
	        categoryService.insertByFilter(category);
        } else {
	        category.setModifiedTime(new Date());
	        categoryService.updateByIdFilter(category);
        }
	    return RestResponse.ok(category);
	}

    @PreAuthorize("@ss.hasAnyPermi('category:course:delete,category:project:delete')")
    @Log(title = "类别管理", businessType = BusinessType.DELETE)
    @RequestMapping(value="/delete/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "类别信息的删除接口（通过id号删除）", notes = "删除类别信息表[category]，作者：lin keqing")
    public RestResponse delete(@PathVariable Integer id) {
	    Category category = categoryService.selectByPrimaryKey(id);
	    category.setIsDeleted(1);
	    categoryService.updateByIdFilter(category);
	    //删除该类别所有课程
	    courseService.deleteAllCourseByCategory(id);
	    return RestResponse.ok();
    }

    @PreAuthorize("@ss.hasAnyPermi('category:course:update,category:project:update')")
    @Log(title = "类别管理", businessType = BusinessType.UPDATE)
    @RequestMapping(value="/changeStatus/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "某个类别的启用状态改变接口（禁用/启用）", notes = "改变某个类别的启用状态[category]，作者：lin keqing")
    public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
	    Category category = categoryService.selectByPrimaryKey(id);
	    Integer newStatus = category.getIsEnabled() == 1 ? 0 : 1;
	    category.setIsEnabled(newStatus);
	    category.setModifiedTime(new Date());
	    categoryService.updateByIdFilter(category);
	    return RestResponse.ok(newStatus);
    }

    @PreAuthorize("@ss.hasAnyPermi('category:course:query,category:project:query')")
	@RequestMapping(value = "/select/{id}", method = RequestMethod.POST, produces = "application/json")
	@ApiOperation(value = "根据id查找类别(编辑按钮调用这个接口)",notes = "返回部分类别信息")
	@ApiImplicitParam(paramType="path", name = "id", value = "类别id", dataType = "int",required = true)
    public RestResponse<CategoryCreateVM> select(@PathVariable Integer id) {
		Category category = categoryService.selectByPrimaryKey(id);
		CategoryCreateVM vm = modelMapper.map(category, CategoryCreateVM.class);
		return RestResponse.ok(vm);
	}

    @PreAuthorize("@ss.hasAnyPermi('category:course:list,category:project:list')")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
	@ApiOperation(value = "类别信息的页面查询接口（无参数查找/按类别名字查找）", notes = "查询类别信息[category]，作者：lin keqing")
    public RestResponse<PageInfo<CategoryResponseVM>> pageList(@RequestBody CategoryPageRequestVM model) {
		if(model != null && StringUtils.isNotBlank(model.getConcreteName())){
			model.setConcreteName(model.getConcreteName().trim());
		}

        PageInfo<Category> pageInfo = categoryService.categoryPage(model);
        PageInfo<CategoryResponseVM> page = PageInfoHelper.copyMap(pageInfo,
                d -> CategoryResponseVM.from(d));
        return RestResponse.ok(page);
    }

	@RequestMapping(value = "/allCategory", method = RequestMethod.POST)
	@ApiOperation(value = "查询所有类别信息的接口（无参数查找/按categoryId查找）", notes = "查询所有类别[category]，作者lin keqing")
	public RestResponse<List<AllCategoryInfoResponseVM>> queryAllCategoryInfo(@RequestBody AllCategoryRequestVM model) {
		List<AllCategoryInfoResponseVM> infoList = categoryService
					.queryAllCategoryInfoList(model.getCategoryId());
		return RestResponse.ok(infoList);
	}


	/**
	 * @explain 查询类别信息表对象  <swagger GET请求>
	 * @param   id
	 * @return  category
	 * @author  lin keqing
	 * @time    Category
	 */
	/*
	@GetMapping("/getCategoryById/{id}")
	@ApiOperation(value = "获取类别信息表信息", notes = "获取类别信息表信息[category]，作者：lin keqing")
	@ApiImplicitParam(paramType="path", name = "id", value = "类别信息表id", required = true, dataType = "Integer")
	public RestResponse<Category> getCategoryById(@PathVariable("id")Integer id){

		try {
			Category category=categoryService.selectByPrimaryKey(id);
			if (category != null) {
				return RestResponse.ok(category);
			} else {
				logger.error("查询类别信息表执行失败："+category.toString());
				return RestResponse.fail(SystemCode.NoDataExist.getCode(),SystemCode.NoDataExist.getMessage());
			}
		} catch (Exception e) {
			logger.error("查询类别信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/


	/**
	 * @explain 添加类别信息表对象
	 * @param   category
	 * @return  int
	 * @author  lin keqing
	 * @time    Category
	 */
	/*
	@PostMapping("/insertSelective")
	@ApiOperation(value = "添加类别信息表", notes = "添加类别信息表[category],作者：lin keqing")
	public RestResponse<Integer> insertSelective(Category category){
		try {
			int rg = categoryService.insertSelective(category);
			if (rg > 0) {
				return RestResponse.ok(rg);
			} else {
				logger.error("添加类别信息表执行失败："+category.toString());
				return RestResponse.fail(SystemCode.InsertDataFail.getCode(),SystemCode.InsertDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("添加类别信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 删除类别信息表对象
	 * @param   id
	 * @return  int
	 * @author  lin keqing
	 * @time    Category
	 */
	/*
	@PostMapping("/deleteByPrimaryKey")
	@ApiOperation(value = "删除类别信息表", notes = "删除类别信息表,作者：lin keqing")
	@ApiImplicitParam(paramType="query", name = "id", value = "类别信息表id", required = true, dataType = "Integer")
	public RestResponse<Integer> deleteByPrimaryKey(Integer id){
		try {
			int reg=categoryService.deleteByPrimaryKey(id);
			if (reg > 0) {
				return RestResponse.ok(reg);
			} else {
				logger.error("删除类别信息表失败ID："+id);
				return RestResponse.fail(SystemCode.DeleteDataFail.getCode(),SystemCode.DeleteDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("删除类别信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 修改类别信息表对象
	 * @param   category
	 * @return  category
	 * @author  lin keqing
	 * @time    Category
	 */
	/*
	@ApiOperation(value = "修改类别信息表", notes = "修改类别信息表[category],作者：lin keqing")
	@PostMapping("/updateByPrimaryKeySelective")
	public RestResponse<Integer> updateByPrimaryKeySelective(Category category){
		try {
			int reg = categoryService.updateByPrimaryKeySelective(category);
			if (reg > 0) {
				return RestResponse.ok(reg);
			} else {
				logger.error("修改类别信息表失败ID："+category.toString());
				return RestResponse.fail(SystemCode.UpdateDataFail.getCode(),SystemCode.UpdateDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("修改类别信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 获取匹配类别信息表
	 * @param   category
	 * @return  List<Category>
	 * @author  lin keqing
	 * @time    Category
	 */
	/*
	@ApiOperation(value = "条件查询类别信息表", notes = "条件查询[category],作者：lin keqing")
	@PostMapping("/queryCategoryList")
	public RestResponse<List<Category>> queryCategoryList(Category category){
		try {
			List<Category> list = categoryService.queryCategoryList(category);
			return RestResponse.ok(list);
		} catch (Exception e) {
			logger.error("获取类别信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
    */
}